package com.personal.gateway.flinkAllCommand.configurationOption.parameterCheck;

import com.personal.gateway.custom.customException.ConfigurationOptionCheckException;
import com.personal.gateway.flinkAllCommand.configurationOption.ConfigurationOption;
import com.personal.gateway.flinkAllCommand.configurationOption.configurationType.ConfigurationTypeListMap;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.personal.gateway.flinkAllCommand.configurationOption.parameterCheck.ParameterCheckListString.LIST_SPLIT_KEY;

/**
 * @author BigHead
 * @date 2022/1/11 10:57
 * @description ParameterCheckString
 */
public class ParameterCheckListMap extends AbstractParameterCheck<List<Map<String, String>>, ConfigurationTypeListMap> {

    public static final String MAP_SPLIT_KEY = ":";

    @Override
    public List<Map<String, String>> abstractCheckValue(ConfigurationOption<List<Map<String, String>>, ConfigurationTypeListMap> configurationOption, String value) {
        if (StringUtils.isNotEmpty(value)) {
            // 校验
            if (value.split(LIST_SPLIT_KEY).length > 1) {
                for (String mapString : value.split(LIST_SPLIT_KEY)) {
                    if (mapString.split(MAP_SPLIT_KEY).length != 2) {
                        throw new ConfigurationOptionCheckException(value, configurationOption);
                    }
                }
            } else {
                throw new ConfigurationOptionCheckException(value, configurationOption);
            }
            // 生成对象
            List<Map<String, String>> listMap = new ArrayList<>();
            for (String mapString : value.split(LIST_SPLIT_KEY)) {
                String[] mapArrays = mapString.split(MAP_SPLIT_KEY);
                listMap.add(
                        new HashMap<String, String>(1) {
                            {
                                put(mapArrays[0], mapArrays[1]);
                            }
                        }
                );
            }
            return listMap;
        }
        return null;
    }
}
